package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import Models.TimeCard;

public class TimeCardPresenter extends AbstractPresenter<TimeCard> {
	final String SINGLEITEM = "timeCard";
	final String MULTIITEM = "timeCards";
	
	public ArrayList<TimeCard> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public TimeCard tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public TimeCard createItemFromJSONObject(JSONObject jsonObject){
		TimeCard card = new TimeCard();
		try{
			card.setComplete(jsonObject.getBoolean("complete"));
			//Set employee
			EmployeeViewPresenter empPresenter = new EmployeeViewPresenter();
			JSONObject jsonEmp = jsonObject.getJSONObject("employee");
			card.setEmployee(empPresenter.createItemFromJSONObject(jsonEmp));
			card.setId(jsonObject.getInt("id"));
			if(!jsonObject.isNull("lunchStart")){
				card.setLunchStart(timeFormat.parse(jsonObject.getString("lunchStart")));
			} else {
				card.setLunchStart(null);
			}
			if(!jsonObject.isNull("lunchStop")){
				card.setLunchStop(timeFormat.parse(jsonObject.getString("lunchStop")));
			} else {
				card.setLunchStop(null);
			}
			card.setProcessed(jsonObject.getBoolean("processed"));
			card.setTimeIn(timeFormat.parse(jsonObject.getString("timeIn")));
			if(!jsonObject.isNull("timeOut")){
				card.setTimeOut(timeFormat.parse(jsonObject.getString("timeOut")));
			} else {
				card.setTimeOut(null);
			}
			return card;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(TimeCard item){
		try{
			JSONObject json = new JSONObject();
			json.put("id", item.getId());
			//Add Employee
			final EmployeeViewPresenter empPresenter = new EmployeeViewPresenter();
			json.put("employee", empPresenter.createJSON(item.getEmployee()));
			json.put("complete", item.isComplete());
			json.put("processed", item.isProcessed());
			json.put("timeIn", getDate(item.getTimeIn()));
			if(item.getTimeOut()!=null){
				json.put("timeOut", getDate(item.getTimeOut()));
			} else {
				json.put("timeOut", JSONObject.NULL);
			}
			if(item.getLunchStart()!=null){
				json.put("lunchStart", getDate(item.getLunchStart()));
			} else {
				json.put("lunchStart", JSONObject.NULL);
			}
			if(item.getLunchStop()!=null){
				json.put("lunchStop", getDate(item.getLunchStop()));
			} else {
				json.put("lunchStop", JSONObject.NULL);
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public TimeCard getEmptyEntity(){
		TimeCard entity = new TimeCard();
		return entity;
	}
}
